#!/bin/sh

# Assigning defaults

query=""
instance="https://nyaa.si"
page="p=1"
max=75
type="c=0_0"
filter="f=0"
modifiers=0
download=0

while [ $# -gt 0 ]; do
	case "$1" in
		-l|--link)
			modifiers=$((modifiers|1))
			shift
			;;
		-r|--rss)
			modifiers=$((modifiers|2))
			shift
			;;
		-d|--download)
			download=1
			shift
			;;
		-t|--type)
			case "$2" in
				all)
					type="c=0_0"
					;;
				anime|art)
					type="c=1_0"
					;;
				anime_mv|art_anime)
					type="c=1_1"
					;;
				anime_english|art_doujin)
					type="c=1_2"
					;;
				anime_other|art_games)
					type="c=1_3"
					;;
				anime_raw|art_manga)
					type="c=1_4"
					;;
				art_pictures)
					type="c=1_5"
					;;
				audio|real_life)
					type="c=2_0"
					;;
				lossless|real_life_pictures)
					type="c=2_1"
					;;
				lossy|real_life_videos)
					type="c=2_2"
					;;
				literature)
					type="c=3_0"
					;;
				literature_english)
					type="c=3_1"
					;;
				literature_other)
					type="c=3_2"
					;;
				literature_raw)
					type="c=3_3"
					;;
				live_action)
					type="c=4_0"
					;;
				live_action_english)
					type="c=4_1"
					;;
				live_action_pv)
					type="c=4_2"
					;;
				live_action_other)
					type="c=4_3"
					;;
				live_action_raw)
					type="c=4_4"
					;;
				picture)
					type="c=5_0"
					;;
				graphic)
					type="c=5_1"
					;;
				photo)
					type="c=5_2"
					;;
				software)
					type="c=6_0"
					;;
				apps)
					type="c=6_1"
					;;
				games)
					type="c=6_2"
					;;
				*)
					printf "Invalid type: %s\n" "$2" 1>&2
					exit 1
					;;
			esac
			shift
			shift
			;;
		-T|--type-manual)
			if ! printf "%s" "$2" | grep -q -E '[0-9]+_[0-9]+'; then
				printf "Invalid type: %s\n" "$2"
				exit 1
			fi
			type="c=$2"
			shift
			shift
			;;

		-f|--filter)
			case "$2" in
				none)
					filter="&f=0"
					;;
				noremakes)
					filter="&f=1"
					;;
				trusted)
					filter="&f=2"
					;;
				*)
					printf "Invalid filter: %s\n" "$2" 1>&2
					exit 1
					;;
			esac
			shift
			shift
			;;
		-m|--max)
			if ! printf "%s" "$2" | grep -E -q '[0-9]+'; then
				printf "Max must be a number\n"
				exit 1
			fi	
			max=$(($2 < 75 ? $2 : 75))
			shift
			shift
			;;
		-p|--page)
			if ! printf "%s" "$2" | grep -E -q '[0-9]+'; then
				printf "Page must be a number\n"
				exit 1
			fi	
			page="p=$2"
			shift
			shift
			;;
		-i|--instance)
			instance=$(printf "%s" "$2" | sed "s/\/^//")
			shift
			shift
			;;
		-s|--sukebei)
			instance="https://sukebei.nyaa.si"	
			shift
			;;
		-v|--version)
			printf "1.5.0\n"
			exit	
			;;
		-h|-?|--help)
			printf "nyaash
Minimal nyaa query tool

USAGE:
nyaash [args] [query] [args]

OPTIONS
-d, --download		open one of the magnets
-f, --filter		select filter (none, noremakes, trusted) (def. none)
-i, --instance	 	specify instance (including protocol)
-l, --link		output request link
-m, --max	 	maximum numbers of results (def.=max=75)
-p, --page	 	choose page
-r, --rss		output rss page (can be combined with -l) 
-s, --sukebei		open one of the magnets
-t, --type		select torrent type (def. all)
-T, --type-manual	like -t but directly specify the value (ex 1_0 for anime)

-h, --help		print help
-v, --version		print version

Accepted torrent types (-t option)
all, anime, anime_mv, anime_english anime_other anime_raw, audio, lossless, lossy, literature, literature_english, literature_other, literature_raw, live_action, live_action_english, live_action_pv, live_action_other, live_action_raw, picture, graphic, photo, software, apps, games, art, art_anime, art_doujin, art_games, art_games, art_pictures, real_life, real_life_pictures, real_life_videos\n"
			exit	
			;;
		*)
			query="q=$1"
			shift
			;;
	esac
done

# Checking output modifiers

webpage=""

case "$modifiers" in
	1)
		curl -G -L -s -w  "\n%{url_effective}\n" --data-urlencode "$query" --data-urlencode "$type" --data-urlencode "$filter" --data-urlencode "$page" "http://0.0.0.0" | sed "s#http://0.0.0.0#${instance%/}#" 2>/dev/null | tail -1
		exit
		;;
	2)	
		curl -G -L -s --data-urlencode "$query" --data-urlencode "$type" --data-urlencode "$filter" --data-urlencode "$page" "$instance"  --data-urlencode "page=rss"
		exit
		;;
	3)
		curl -G -L -s -w  "\n%{url_effective}\n" --data-urlencode "$query" --data-urlencode "$type" --data-urlencode "$filter" --data-urlencode "$page" http://0.0.0.0  --data-urlencode "page=rss" | sed "s#http://0.0.0.0#${instance%/}#" 2>/dev/null | tail -1
		exit	
		;;
	*)
		webpage="$(curl -G -L -s -w  "\n%{url_effective}\n" --data-urlencode "$query" --data-urlencode "$type" --data-urlencode "$filter" --data-urlencode "$page" http://0.0.0.0 | sed "s#http://0.0.0.0#${instance%/}#" 2>/dev/null | tail -1)"
		;;
esac


# Querying nyaa and filtering torrent table
torrents=$(lynx -source "$webpage" | grep -A 1000000000 '<tbody>' | grep -B 1000000000 '</tbody>' | sed -e '/<\/tbody>/d' -e '/<tbody>/d')
# Parsing torrent table
titles=$(printf "%s" "$torrents" | sed '/class="comments"/{N;d}' | grep -A 1 '<td colspan="2">' | sed -e '/<td colspan="2">/d' -e '/^--/d' -e 's/<\/a>//g' -e 's/^.*<a.*>//')
magnets=$(printf "%s" "$torrents" | grep -E "<a href" | grep -o 'magnet:?xt=urn:btih:[0-9a-f]*')
size=$(printf "%s" "$torrents" | grep -o -E '<td class="text-center">[0-9a-zA-Z. ]*</td>' | grep -o -E '[0-9]{1,4}(\.[0-9]{,4})? ([TGMKk]i)?B')
date=$(printf "%s" "$torrents" | grep -o -E '<td class="text-center" data-timestamp="[0-9]*">.*</td>' | grep -o -E '[0-9]{4,4}-[0-9]{2,2}-[0-9]{2,2} [0-9]{2,2}:[0-9]{2,2}( ?([APap][mM]))?')
type=$(printf "%s" "$torrents" | grep '<img src.*alt="' | sed -e 's/^.*alt="//' -e 's/" class="category-icon">//')
extras=$(printf "%s" "$torrents" | grep -o -E '<td class="text-center">[0-9]*</td>' | sed -e 's/<td class="text-center">//' -e 's/<\/td>//')

# Decoding html chars

titles="$(printf "%s" "$titles" | sed 's/&nbsp;/ /g; s/&amp;/\&/g; s/&lt;/\</g; s/&gt;/\>/g; s/&quot;/\"/g; s/&#39;/\'"'"'/g; s/&ldquo;/\"/g; s/&rdquo;/\"/g; s/&#34;/\"/g')"


# Generating output
if [ -n "$titles" ]; then
	length=$(printf "%s\n" "$magnets" | wc -l)
	length=$((length>max ? max : length))
	i=1
	while [ $length -ge $i ]; do
		printf "%s [%s]: %s\n" "$i" "$(printf "%s" "$type" | sed -n "$i"p)" "$(printf "%s" "$titles" | sed -n "$i"p)"
		printf "%s\n" "$(printf %s "$magnets" | sed -n "$i"p)"
		printf "size: %s date: %s\n" "$(printf "%s" "$size" | sed -n "$i"p)" "$(printf "%s" "$date" | sed -n "$i"p )"  
		printf "seeds: %s leechs: %s downloads: %s\n\n" "$(printf "%s" "$extras" | sed -n "$((3*i-2))"p )" "$(printf "%s" "$extras" | sed -n "$((3*i-1))"p )" "$(printf "%s" "$extras" | sed -n "$((3*i))"p )"
		i=$((i+1))
	done

	# download prompt

	if [ $download -eq 1 ]; then
		selected=0
		while [ "$selected" -gt "$length" ] || [ "$selected" -le 0 ]; do
			printf "ID of the file to download (non-integer to exit)\n"
			read -r selected
			if ! printf "%s" "$selected" | grep -E -q "^ *[0-9]+ *$"; then
				selected=0
				break
			fi
		done
		if [ "$selected" -gt 0 ]; then
			xdg-open "$(printf "%s" "$magnets" | sed -n "$selected"p)" &
		fi
	fi

fi
